package com.chaoyong.higo.fragment;

import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.entity.StringEntity;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.chaoyong.higo.R;
import com.chaoyong.higo.activity.ProductDetailActivity;
import com.chaoyong.higo.adapter.PurchaseRecordAdapter;
import com.chaoyong.higo.base.BaseFragment;
import com.chaoyong.higo.bean.GoodsRecordBean_z;
import com.chaoyong.higo.net.OApi;
import com.chaoyong.higo.utils.EmptyUtil;
import com.chaoyong.higo.utils.JLog;
import com.chaoyong.higo.utils.PrefUtils;
import com.chaoyong.higo.utils.V;
import com.chaoyong.higo.view.XListView;
import com.chaoyong.higo.view.XListView.IXListViewListener;
import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;

/**
 * 云筹记录-已揭晓
 * @author zk
 *
 */
public class FragRecordKnown extends BaseFragment implements IXListViewListener, OnItemClickListener {
	
	private static final String ClassName = FragRecordKnown.class.getName();
	
	private XListView order_list_view;
	private PurchaseRecordAdapter adapter;
	
	private GoodsRecordBean_z bean;
	
private List<GoodsRecordBean_z.DataEntity.ListEntity> entity;
	
	private String uid;
	private int page = 5;
	

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

		mView = inflater.inflate(R.layout.frag_records, container, false);
		return mView;
	}

	@Override
	public void findView() {
		order_list_view = V.f(mView, R.id.order_list_view);
		order_list_view.setPullLoadEnable(true);
		order_list_view.setPullRefreshEnable(true);
		order_list_view.setXListViewListener(this);
		order_list_view.setOnItemClickListener(this);
	}

	@Override
	public void init() {
		
		uid = PrefUtils.getString(mContext, "userId", "1");
		
		adapter = new PurchaseRecordAdapter(mContext);
		order_list_view.setAdapter(adapter);
	}
	
	@Override
	public void onStart() {
		super.onStart();
		//uid = PrefUtils.getString(mContext, "userId", "1");
		// httpGetRecords(uid, "15", "end");
		
		httpGetRecords(uid, "0", "end");
	}

	/**
	 * 云筹记录
	 * 
	 * @param uid
	 *            用户id
	 * @param limit
	 *            数据限制条数
	 * @param status
	 *            请求那个选项的数据 ("":全部，"ing":进行中,"end":已结束)
	 */
	private void httpGetRecords(String uid, String limit, String status) {
		HttpUtils utils = new HttpUtils();
		RequestParams param = new RequestParams();
		try {
			JSONObject jsonObject = new JSONObject();
			JSONObject info = new JSONObject();

			jsonObject.putOpt("model", "GoodsRecord");
			jsonObject.putOpt("function", "cloudBuyRecord");
			jsonObject.putOpt("info", info);

			info.putOpt("uid", uid);
			info.putOpt("limit", limit);
			info.putOpt("status", status);

			param.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		utils.send(HttpMethod.POST, OApi.appport_appMember, param, new RequestCallBack<String>() {

			@Override
			public void onFailure(HttpException arg0, String arg1) {
				JLog.i(ClassName, arg0.getMessage());
			}

			@Override
			public void onSuccess(ResponseInfo<String> arg0) {
				JLog.i(ClassName, arg0.result);
				try {
					JSONObject jsonObject = new JSONObject(arg0.result);
					String status = jsonObject.getString("status");
					Gson gson = new Gson();
					if (status.equals("1")) {
						bean = gson.fromJson(arg0.result, GoodsRecordBean_z.class);
						entity = bean.getData().getList();

						if (!EmptyUtil.isEmpty(entity)) {
							adapter.setList(entity);
						}
						// // showToast(entity.size() + "");
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
				//
			}
		});
	}
	
	
	@Override
	public void onRefresh() {
		// TODO Auto-generated method stub
		//loadMore(uid, page + "", "");
		Toast.makeText(mContext, "已经刷新了", 0).show();
		order_list_view.stopRefresh();
	}

	@Override
	public void onLoadMore() {
		// TODO Auto-generated method stub
		loadMore(uid, page + "", "end");
		order_list_view.stopLoadMore();
	}
	
	private void loadMore(String uid, String limit, String status) {
		HttpUtils utils = new HttpUtils();
		RequestParams param = new RequestParams();
		try {
			JSONObject jsonObject = new JSONObject();
			JSONObject info = new JSONObject();

			jsonObject.putOpt("model", "GoodsRecord");
			jsonObject.putOpt("function", "cloudBuyRecord");
			jsonObject.putOpt("info", info);

			info.putOpt("uid", uid);
			info.putOpt("limit", limit);
			info.putOpt("status", status);

			param.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		utils.send(HttpMethod.POST, OApi.appport_appMember, param, new RequestCallBack<String>() {

			@Override
			public void onFailure(HttpException arg0, String arg1) {
				JLog.i(ClassName, arg0.getMessage());
			}

			@Override
			public void onSuccess(ResponseInfo<String> arg0) {
				JLog.i(ClassName, arg0.result);
				try {
					JSONObject jsonObject = new JSONObject(arg0.result);
					String status = jsonObject.getString("status");
					Gson gson = new Gson();
					if (status.equals("1")) {
						bean = gson.fromJson(arg0.result, GoodsRecordBean_z.class);
						entity.addAll(bean.getData().getList());

						if (!EmptyUtil.isEmpty(entity)) {
							adapter.setList(entity);
							page += 5;
							order_list_view.stopLoadMore();
						}
						// // showToast(entity.size() + "");
					}else{
						showToast("已经没有更多记录了");
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
				//
			}
		});
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		// TODO Auto-generated method stub
		goDetails(entity.get(position - 1).getGoods_id(),entity.get(position - 1).getExpect());
	}

	private void goDetails(final String goods_id, final String expect) {
		// TODO Auto-generated method stub
		JSONObject json = new JSONObject();
		JSONObject info = new JSONObject();
		try {
			info.put("goods_id", goods_id);
			info.put("expect", expect);
		} catch (JSONException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		try {
			json.put("path", "/M/Goods/winningDatail");
			json.put("info", info);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		RequestParams params = new RequestParams();
		try {
			params.setBodyEntity(new StringEntity(json.toString(), "utf-8"));
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		HttpUtils utils = new HttpUtils();
		utils.send(HttpMethod.POST, OApi.appport_winningGoods, params, new RequestCallBack<String>() {

			@Override
			public void onFailure(HttpException arg0, String arg1) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void onSuccess(ResponseInfo<String> arg0) {
				// TODO Auto-generated method stub
				String result = arg0.result;
				try {
					JSONObject jso = new JSONObject(result);
					if(jso.getInt("status") == 1){
						JSONObject datajs = jso.getJSONObject("data");
						JSONObject goods_info_js = datajs.getJSONObject("goods_info");
						JSONArray ja = goods_info_js.getJSONArray("cover_img");
						
						String goods_img = (String) ja.get(0);
						String head_img = goods_info_js.getString("user_img");
						String goodsInfo = goods_info_js.getString("goods_info");
						String price = goods_info_js.getString("goods_price");
						
						Intent intentt = new Intent(mContext, ProductDetailActivity.class);
						intentt.putExtra("goods_img", goods_img);
						intentt.putExtra("head_img", head_img);
						intentt.putExtra("goodsInfo", goodsInfo);
						intentt.putExtra("price", price);
						intentt.putExtra("goods_id", goods_id);
						intentt.putExtra("expect", expect);
						startActivity(intentt);
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
	}

}
